﻿using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using System.Reflection;

using Freeform;


namespace Client
{
    public class TileLevelReader : ContentTypeReader<TileMap2D>
    {
        protected override TileMap2D Read(ContentReader input, TileMap2D existingInstance)
        {
            //We grab the layer, object and texture counts so as to loop through all avaible data the right amount of times.
            Int32 layerCount = input.ReadInt32();
            Int32 objectCount = input.ReadInt32();
            TileMap2D map = new TileMap2D(layerCount, objectCount);

            Int32 textureCount = input.ReadInt32();

            for (int i = 0; i < textureCount; i++)
            {
                //We read the output in order from the TileLevelWriter.
                map.TileSet = input.ReadExternalReference<Texture2D>();
                map.TileWidth = input.ReadInt32();
                map.TileHeight = input.ReadInt32();
            }

            for (int i = 0; i < layerCount; i++)
            {
                //We make sure to init stuff before we use it.
                map.Layers[i] = new TileLayer2D();
                Int32[,] a;
                map.Layers[i].Width = input.ReadInt32();
                map.Layers[i].Height = input.ReadInt32();
                a = new Int32[map.Layers[i].Width, map.Layers[i].Height];

                for (int y = 0; y < map.Layers[i].Height; y++)
                    for (int x = 0; x < map.Layers[i].Width; x++)
                        a[y, x] = input.ReadInt32();;

                //We assign the temp vars to their places.
                map.Layers[i].MapGrid = a;
                map.Layers[i].Name = input.ReadString();
            }

            //We init our object list and populate it with the read data.
            map.Objects.ObjectList = new List<Object2D>();
            for (int i = 0; i < objectCount; i++)
            {
                Object2D a = new Object2D();
                a.GridID = input.ReadInt32();
                a.X = input.ReadInt32();
                a.Y = input.ReadInt32();
                a.Width = input.ReadInt32();
                a.Height = input.ReadInt32();
                map.Objects.ObjectList.Add(a);
            }

            //Return yo map homie.
            return map;
        }
    }

}
